/*
 * ==================================================
 * 项目开发者：JerryStark
 * 开发者Email：4771007@qq.com
 * 开发者QQ:4771007
 * 开发范围：web，wap，android,ios,osx or win or linux 应用
 * ==================================================
 */
package RTPower;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 端口监听类
 * <br>分为服务器端和客户端
 *
 * @author jerry
 */
abstract public class RTSocket {

    /**
     * 默认服务器端监听端口
     */
    public int ServerPort = 8080;

    /**
     * 服务器端通讯链接
     */
    public ServerSocket SerSocket;

    /**
     * 服务器端线程
     */
    public Thread SerThread;

    /**
     * 服务器端线程默认状态
     */
    public boolean SerStatus = true;

    /**
     * 开始服务器端监听
     *
     */
    public void StartServer() {
        SerStatus = true;
        //建立新线程执行监听,不在主线程执行
        SerThread = new Thread(() -> {
            try {
                //建立监听服务器的主线程和服务器连接
                SerSocket = new ServerSocket(ServerPort);
                System.out.println("建立端口监听:" + ServerPort);
                //循环执行等待客户端连接
                while (SerStatus) {
                    Socket one_client = SerSocket.accept();
                    new ServerOneAcceptThread(one_client).start();
                }
                
            } catch (IOException ex) {
                System.err.println(ex.getMessage());
//                Logger.getLogger(RTSocket.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            System.err.println("监听结束.");
            
        });
        SerThread.setName("ServerSocket");
        SerThread.start();
    }

    /**
     * 结束服务器端监听
     */
    public void StopServer() {
        //结束监听
        SerStatus = false;
        
        try {
            SerSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(RTSocket.class.getName()).log(Level.SEVERE, null, ex);
        }
        SerThread = null;
    }

    /**
     * 内部类,单个新线程执行接收客户端的处理
     */
    class ServerOneAcceptThread extends Thread {

        /**
         * 单个客户端的socket
         */
        Socket OneClientSocket = null;

        /**
         * 初始化把传入的客户端连接赋值给内部类全局使用
         *
         * @param one_client
         */
        public ServerOneAcceptThread(Socket one_client) {
            System.out.println("获得客户端连接......" + one_client);
            this.OneClientSocket = one_client;
            this.setName("client_" + this.getName());
        }

        /**
         * 执行线程
         */
        public void run() {
            try {
                String client_ip = OneClientSocket.getLocalAddress().getHostAddress();
                //获得输入和输出
                OutputStream writer = OneClientSocket.getOutputStream();
                InputStream input_stream = OneClientSocket.getInputStream();
                
                InputStreamReader ReaderData = new InputStreamReader(input_stream);
                BufferedReader br = new BufferedReader(ReaderData);
//                OneClientSocket.setSoTimeout(100);

                StringBuilder msg = new StringBuilder();
                
                msg.append(br.readLine());
                System.out.println("获得客户端[" + client_ip + "]传入信息:" + msg.toString());

                //提交给输出处理
                msg.append(client_ip);
                String back_string = ServerBackMsg(client_ip, writer, msg);
                //处理结果返回字符串则写出返回的,否则默认
                if (back_string.length() > 0) {
                    writer.write(back_string.getBytes());
                } else {
                    writer.write(GetServerDefString().getBytes());
                }
                //关闭
                writer.close();
                
                ReaderData.close();
                br.close();
                OneClientSocket.close();
                System.out.println("关闭单个客户端连接."+this.getName());
                
            } catch (IOException ex) {
                Logger.getLogger(RTSocket.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        /**
         * 获取默认的返回字符串
         *
         * @return
         */
        private String GetServerDefString() {
            String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n"
                    + "Content-Length: 23\r\n" + "\r\n" + "<h1>File Not Found</h1>";
            return errorMessage;
        }
        
    }

    /**
     * 处理传入信息并返回数据给客户端
     *
     * @param client_ip 客户端ip
     * @param writer 写出流
     * @param inputstring 传入的内容
     * @return
     */
    abstract public String ServerBackMsg(String client_ip, OutputStream writer, StringBuilder inputstring);
    
}
